package it.tcon.xbeedriver.resmanager;

import org.apache.log4j.Logger;

import it.tcon.xbeedriver.XBeeNode;
import it.tcon.xbeedriver.XBeeNodeException;
import it.tcon.xbeedriver.XBeeNodeList;

import com.rapplogic.xbee.api.zigbee.ZNetNodeIdentificationResponse;

import com.rapplogic.xbee.util.ByteUtils;
/**
 * This manager handle any node identification message, that a router or an end device 
 * sends to identify itself to the coordinator (when AO=0).
 * It's similar to a response from a ND command, but it's always sent when a node restart itself or when a node is near a PAN
 * @author Marco Vettorello
 *
 */
public class ZNetNodeIdentifierManager {

	//private ZNetNodeIdentificationResponse response;
	private XBeeNodeList list;
	private Logger logger = Logger.getLogger(ZNetNodeIdentifierManager.class);
	
	public ZNetNodeIdentifierManager(){
		
	}
	/**
	 * Constructor for a ZNetNodeIdentifier manager.
	 * It check if the node was present on the network in the past and, if not, add it to the shared node list.
	 * @param rsp the response arrived to the receiver thread.
	 * @param list the shared list of all xBeeNode
	 */
	public ZNetNodeIdentifierManager(ZNetNodeIdentificationResponse rsp,XBeeNodeList list){
		XBeeNode newNode;
		//XBeeNodeType newType;
		ZNetNodeIdentificationResponse response = rsp;
		String address = ByteUtils.toBase16(response.getRemoteAddress64().getAddress());
		logger.debug("Message start Checking by ZNetNodeIdentifierManager :"+ByteUtils.toBase16(response.getRemoteAddress64().getAddress()));
		
		this.list = list;
		if(!this.list.isPresent(address))
		{	
			logger.debug("Address:"+address);
			//newType = new XBeeNodeType(response.getDeviceType().getValue());
			newNode = new XBeeNode(response.getRemoteAddress64(),response.getDeviceType());
			newNode.setActive(true);
			//newNode.setAddress64(response.getRemoteAddress64());
			//ewNode.setType(response.getDeviceType());
			//TODO add more information in the node from the NodeIdentification Message
			//TODO add this packet with this date on the packet list of this node ???
			
			try {
				this.list.addNode(newNode);
				logger.debug("New Node Added. Address:"+newNode.getAddress64String());
			} catch (XBeeNodeException e) {
				logger.error("Node already exist or not a correct address. It's inserted on the list");
				e.printStackTrace();
			}

		}
		else{
			XBeeNode node = this.list.getNode(address);
			node.setActive(true);
			this.list.updateNode(node);
			logger.debug("The Address is already present on the list");
		}
		logger.debug("Message Checked by ZNetNodeIdentifierManager");

		
		
	}
}
